package text.text1;

public class LoopNode <T>{
    Node<T> head = new Node();
    /**
     * 循环语句
     */

    public LoopNode(){
        head.next =head;
    }
    /**
     * 头插法
     */
    public void headAtHead(T date){
        Node<T> node = new Node<>();
        node.date = date;
        node.next=head.next;
        head.next = node;
    }
    /**
     * 尾插法
     */
    public void headAtTail(T date){
        Node<T> node = new Node<>();
        Node p = head;
        node.date = date;

        while (p.next!=head){
            p=p.next;
        }

        node.next=p.next;
        p.next=node;
    }
    /**
     * 任意头部头插法
     */
    public void headBefor(T old , T date){
        Node<T> p = head;
        Node<T> node = new Node<>();
        node.date = date;

        while(p.next!=head && p.next.date.equals(old)){
            p=p.next;
        }
        if(p.next==head){
            System.out.println("你所输入的"+old+"不存在，请输入有效值");
            return;
        }

        node.next = p.next;
        p.next = node;

    }
    /**
     * 任意尾部插入法
     */
    public void headLater(T old, T date){
        Node<T> p = head.next;
        Node<T> node = new Node<>();
        node.date = date;

        while(p.next!=head && p.next.date.equals(old)){
            p=p.next;
        }
        if(p.next==head){
            System.out.println("你所输入的"+old+"不存在，请输入有效值");
            return;
        }

        node.next = p.next;
        p.next = node;
    }
    /**
     * 移除
     */
    public void remove(T date) {
        Node node = head;
        while (node.next != null && !node.next.date.equals(date)) {
            node = node.next;
        }
        if (node.next == null) {
            System.out.println("找不到" + date + ",请输入有效的值");
            System.out.println();
            return;
        }
        node.next = node.next.next;
    }

    /**
     * 清零
     */
    public void clean() {
        head.next = null;
        return;
    }

    /**
     * 获取多少个数
     */
    public int getCount() {
        int n = 0;
        Node count = head;
        while (!count.next.equals(null)) {
            count = count.next;
            n++;
        }
        return n;
    }

    /**
     * 打印
     */
    public void display(){
        if(head.next==head){
            System.out.println("这是一张空表");
            return;
        }

        for(Node node = head.next;node!=head;node=node.next){
            System.out.print(node.date +"  ");
        }
        System.out.println();
    }
}
